package com.binzaijun.stock.service;

import com.alibaba.fastjson2.JSONObject;
import com.binzaijun.stock.config.ElasticsearchConfig;
import com.binzaijun.stock.domain.StockChange;
import com.binzaijun.stock.domain.StockInfo;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class ElasticsearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ElasticsearchConfig esConfig;

    private static final String TYPE = "_doc";

    /**
     * 批量导入股票异动数据
     */
    public boolean bulkIndexStockChanges(List<StockChange> stockChangeList) {
        if (stockChangeList == null || stockChangeList.isEmpty()) {
            log.warn("股票异动数据列表为空");
            return false;
        }

        try {
            BulkRequest bulkRequest = new BulkRequest();

            for (StockChange stockChange : stockChangeList) {
                bulkRequest.add(new IndexRequest(esConfig.getStockChangeIndex(), TYPE)
                        .id(stockChange.getStockSymbol() + "-" + stockChange.getDate())
                        .source(JSONObject.toJSONString(stockChange), XContentType.JSON));
            }

            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (response.hasFailures()) {
                log.error("批量导入失败: {}", response.buildFailureMessage());
                return false;
            }
            log.info("批量导入成功, 导入 {} 条记录", stockChangeList.size());
            return true;
        } catch (Exception e) {
            log.error("批量导入股票异动数据失败", e);
            return false;
        }
    }

    /**
     * 搜索股票信息
     */
    public SearchResponse searchStockInfo(String queryString) {
        try {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

            if (queryString == null || queryString.trim().isEmpty()) {
                sourceBuilder.query(QueryBuilders.matchAllQuery());
            } else {
                String[] fields = {"stock_name.pinyin", "stock_name.hanlp", "stock_symbol"};
                MultiMatchQueryBuilder query = QueryBuilders.multiMatchQuery(queryString, fields)
                        .type(MultiMatchQueryBuilder.Type.BEST_FIELDS)
                        .tieBreaker(0.1f);
                sourceBuilder.query(query);
            }

            SearchRequest request = new SearchRequest(esConfig.getStockInfoIndex());
            request.source(sourceBuilder);
            return client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("搜索股票信息失败: {}", queryString, e);
            return null;
        }
    }

    /**
     * 批量导入股票基本信息
     */
    public boolean bulkIndexStockInfo(List<StockInfo> stockInfoList) {
        if (stockInfoList == null || stockInfoList.isEmpty()) {
            log.warn("股票信息列表为空");
            return false;
        }

        try {
            BulkRequest bulkRequest = new BulkRequest();

            for (StockInfo stockInfo : stockInfoList) {
                bulkRequest.add(new IndexRequest(esConfig.getStockInfoIndex(), TYPE)
                        .id(stockInfo.getStockSymbol())
                        .source(JSONObject.toJSONString(stockInfo), XContentType.JSON));
            }

            BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (response.hasFailures()) {
                log.error("批量导入股票信息失败: {}", response.buildFailureMessage());
                return false;
            }
            log.info("批量导入股票信息成功, 导入 {} 条记录", stockInfoList.size());
            return true;
        } catch (Exception e) {
            log.error("批量导入股票信息失败", e);
            return false;
        }
    }

    /**
     * 获取客户端（特殊用途）
     */
    public RestHighLevelClient getClient() {
        return client;
    }
}
